package com.xiu.travel.filter;

import com.xiu.travel.exception.Asserts;
import com.xiu.travel.security.pojo.SecurityUser;
import com.xiu.travel.util.JwtUtil;
import com.xiu.travel.util.api.ResultCode;
import com.alibaba.fastjson2.JSONObject;
import com.xiu.travel.config.LogPathUrlsConfig;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * JWT解析
 *
 * @author : qianlanyuyun
 * @since : 2023/3/25 13:22
 */

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    @Autowired
    private LogPathUrlsConfig logPathUrlsConfig;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        SecurityUser securityUser;
        Claims claims;
        //获取token
        String token = request.getHeader("token");
        log.info("{}", request.getRequestURI());

        Cookie[] cookies = request.getCookies();
        if (!Objects.isNull(cookies)) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
            log.info("token:{}", token);
        }

        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        try {
            claims = JwtUtil.parseJWT(token);
            securityUser = JSONObject.parseObject(claims.getSubject(), SecurityUser.class);
            log.info("claims:{}", securityUser);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("excepiton", ResultCode.UNAUTHORIZED);
            Asserts.fail(ResultCode.UNAUTHORIZED);
            throw new RuntimeException("token非法");
        }
        log.info("securityUser:{}", securityUser);
        if (Objects.isNull(securityUser)) {
            Asserts.fail("用户未登录");
        }

        //存入SecurityContextHolder
        //获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 用户日志操作

//        saveSysLog(request, isLofFlag(request));
        //放行

        filterChain.doFilter(request, response);
    }

    private boolean isLofFlag(HttpServletRequest request) {
        boolean lofFlag = false;
        final AntPathMatcher antPathMatcher = new AntPathMatcher();
        List<String> paths = logPathUrlsConfig.getUrls();

        for (String path : paths
        ) {
            if (antPathMatcher.match(path, request.getRequestURI())) {
                lofFlag = true;
            }

        }
        return lofFlag;
    }

    private void saveSysLog(HttpServletRequest request, boolean lofFlag) throws IOException {
        if (lofFlag) {
            HashMap<String, String> map = new HashMap<String, String>(16);
            Map<String, String[]> paramMap = request.getParameterMap();
            for (String key : paramMap.keySet()) {
                String[] values = paramMap.get(key);
                for (String value : values) {
                    log.info(key + " = " + value);

                    map.put(key, value);
                }
            }
            String param = JSONObject.toJSONString(map);
        }
    }
}

